<?php

namespace App\Http\Controllers\App;

use App\App\Services\ApplyService;
use App\App\Services\VMSService;
use App\Contracts\Services\Storage\StorageService as StorageServiceContract;
use App\App\Services\StorageService;
use App\Models\Enroll\Enroll;
use App\Morefun\Publishing\Publisher;
use Carbon\Carbon;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpFoundation\File\Exception\UploadException;

class ApplyController extends \App\Http\Controllers\Controller
{
    protected $apply;

    public function __construct(ApplyService $applyService)
    {
        $this->apply = $applyService;
    }

    public function widgets(StorageServiceContract $storage, $activityId)
    {
        if (!Uuid::isValid($activityId)) {
            return ['code' => 10000, 'message' => 'ID不合法'];
        }

        $activity = $this->apply->getOne($activityId);

        if (null == $activity) {
            return ['code' => 10000, 'message' => '活动不存在',];
        }

        $applied = Enroll::query()->where('activities_id', $activityId)->count();
        $shares = json_decode($activity->shares, true);
        $rule = json_decode($activity->rule,true);
        $thumb = Arr::get($shares, 'icon', '');
        if(empty($thumb)){
            $thumb = Arr::get($shares, 'thumb', '');
        }
        return [
            "code" => 200,
            "data" => [
                'activity' => [
                    'id' => $activityId,
                    'name' => $activity->name,
                    'isShowEnrollNumber' => Arr::get($rule, 'showEnrollNumberOn', ''),
                    'description' => $activity->description,
                    'start_time' => date('Y.m.d H:i', strtotime($activity->startTime)),
                    'end_time' => date('Y.m.d H:i', strtotime($activity->endTime)),
                    'background_image' => $storage->toHttpUrl($activity->backgroundImg),
                    'publishing' => \GuzzleHttp\json_decode($activity->publishing_ways, true),
                    'shares' => [
                        'isopen' => Arr::get($shares, 'isopen', 'off'),
                        'title' => Arr::get($shares, 'title', ''),
                        'content' => Arr::get($shares, 'content', ''),
                        'thumb' => $storage->toHttpUrl($thumb),
                    ],
                    'applied' => $applied,
                    'app_url' => $activity->app_url,
                ],
                "widgets" => $this->apply->getWidgets($activityId),
            ]
        ];
    }

    public function store(Request $request, $activityId)
    {
        if (!Uuid::isValid($activityId)) {
            return ['code' => 10000, 'message' => 'ID不合法'];
        }

        if (null === ($activity = $this->apply->getOne($activityId))) {
            return ['code' => 10000, 'message' => '您所提交的活动不存在',];
        }

        if ($activity->isPause) {
            return ['code' => 10000, 'message' => '活动已暂停，暂时无法报名',];
        }

        $now = Carbon::now()->format('Y-m-d H:i:s');

        if ($now > $activity->endTime) {
            return ['code' => 10000, 'message' => '活动已结束'];
        }

        if ($now < $activity->startTime) {
            return ['code' => 10000, 'message' => '活动还未开始'];
        }

        list($canRepeat, $rules, $messages) = $this->apply->analysisRules($activityId);

        if (!$canRepeat) {
            if ($this->apply->signed($activityId, $request->input('mobile'))) {
                return ['code' => 10000, 'message' => '这个手机号码已经报名了活动'];
            }
        }

        $this->validate($request, $rules, $messages);
        $data = $request->request->all();
        $ignoreKeys = ['mobile', 'name', 'enrollPay', 'upload_content'];
        $data = $this->arrayStringReplace($data, '', null);
        $input = [
            'activities_id' => $activityId,
            'mobile' => Arr::get($data, 'mobile'),
            'name' => htmlspecialchars(Arr::get($data, 'name', '')),
            'enrollPay' => 0,
            'content' => Arr::get($data, 'upload_content', []),
            'extfield' => Arr::except($data, $ignoreKeys),
        ];

        $enroll = new Enroll();
        $enroll->fill($input);

        if ($enroll->save()) {
            return ['code' => 200, 'message' => 'success'];
        }

        return ['code' => 10000, 'message' => '报名存储失败'];
    }

    protected function arrayStringReplace(array $data, $replaceStr, $search)
    {
        if (!is_array($data)) {
            return $data;
        }
        foreach ($data as $key => $val) {
            if(is_array($val)){
                $this->arrayStringReplace($val,$replaceStr,$search);
            }else if($val === $search) {
                $data[$key] = $replaceStr;
            }
        }
        return $data;
    }

    public function upload(Request $request, $activityId)
    {
        if (!Uuid::isValid($activityId)) {
            return ['code' => 10000, 'message' => 'ID不合法'];
        }

        if (null === ($activity = $this->apply->getOne($activityId))) {
            return ['code' => 10000, 'message' => '您所提交的活动不存在',];
        }

        if ($activity->isPause) {
            return ['code' => 10000, 'message' => '活动已暂停，暂时无法上传文件',];
        }

        $now = Carbon::now()->format('Y-m-d H:i:s');

        if ($now > $activity->endTime) {
            return ['code' => 10000, 'message' => '活动已结束'];
        }

        if ($now < $activity->startTime) {
            return ['code' => 10000, 'message' => '活动还未开始'];
        }

        $rule = ['required', 'file'];
        $needUploadVideo = in_array($request->get('type'), ['video', 'audio'], false);


        if ($needUploadVideo) {
            //$rule[] = 'file';
            $max = 200 * 1024; // 10M改成50M
        } else {
            //$rule[] = 'image';
            $max = 5 * 1024;
        }

        $rule[] = 'mimes:jpeg,bmp,png,jpg,gif,mp4,avi,mov,qt,mp3,ogg,doc,docx,xls,xlsx,ppt,pptx,pdf,txt';
        $rule[] = sprintf('max:%s', $max);

        $this->validate($request, [
            'upfile' => $rule,
        ], [
            'upfile.mimes' => '上传文件格式错误',
        ]);

        $file = $request->file('upfile');

        if ($needUploadVideo) {
            $flag = $this->vmsHandler($file);
        } else {
            $flag = $this->ossHandler($file);
        }

        return ['code' => 200, 'message' => 'success', 'data' => $flag];
    }

    protected function vmsHandler($file)
    {
        $VMSService = Container::getInstance()->make(VMSService::class);
        $VMSService->uploadVideoTmp($file);
        $res = $VMSService->ftpUploadVideo();

        if (!is_array($res)) {
            throw new UploadException("Upload Server Error", 504);
        }

        return Arr::get(Arr::first($res), 'id');
    }

    protected function ossHandler($file)
    {
        $storage = Container::getInstance()->make(StorageService::class);
        $urls = $storage->storeAsTmpImage($file);
        @unlink($file);

        return Arr::get($urls, 'original');
    }
}
